<template>
	<div class="map-container">
		<baidu-map class="bm-view" :center="center" :zoom="zoom" :scroll-wheel-zoom="true" @ready="mapReady">
			<!-- 当前位置标记 -->
			<bm-marker :position="center" :dragging="true" @click="infoWindowOpen">
				<bm-info-window :show="showInfoWindow" @close="infoWindowClose">
					{{ addressInfo }}
				</bm-info-window>
			</bm-marker>

			<!-- 地图控件 -->
			<bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
			<bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" @locationSuccess="locationSuccess">
			</bm-geolocation>

			<!-- 搜索控制面板 -->
			<div class="search-controls">
				<el-button @click="searchInCircleArea" type="primary" size="small">
					搜索3公里内剧场/体育馆
				</el-button>

				<!-- 搜索结果面板 -->
				<div v-if="searchResults.length > 0" class="result-panel">
					<div class="result-count">找到 {{ searchResults.length }} 个结果</div>
					<div class="result-list">
						<div v-for="(item, index) in searchResults" :key="index" class="result-item"
							@click="centerMap(item.point)">
							<div class="item-header">
								<span class="item-type"
									:class="item.type === '剧场' ? 'theater' : 'stadium'">{{ item.type }}</span>
								<span class="item-title">{{ item.title }}</span>
							</div>
							<div class="item-details">
								<span class="item-distance">{{ item.distance }}米</span>
							</div>
						</div>
					</div>
				</div>

				<!-- 无结果提示 -->
				<div v-else-if="searchPerformed && searchResults.length === 0" class="no-results">
					未找到相关场所
				</div>
			</div>
		</baidu-map>
	</div>
</template>


<script>
	export default {
		data() {
			return {
				center: {
					lng: 116.404,
					lat: 39.915
				},
				zoom: 15,
				showInfoWindow: false,
				addressInfo: '正在获取位置信息...',
				searchText: '',
				mapInstance: null,
				BMap: null,
				// 数据属性
				searchKeywords: ['剧场', '体育馆'],
				searchRadius: 3000,
				maxResults: 15,
				searchResults: [],
				resultMarkers: [],
				circleOverlay: null,
				searchPerformed: false, // 新增：标记是否已执行搜索
				searchCompletedCount: 0 // 新增：跟踪已完成的搜索数量
			}
		},
		errorCaptured(err, vm, info) {
			console.error('Vue错误捕获:', err, info)
			return false
		},

		// 添加生命周期钩子检查
		mounted() {
			console.log('组件已挂载')
		},
		methods: {

			mapReady({
				BMap,
				map
			}) {
				console.log('地图API准备就绪:', {
					BMap: !!BMap,
					map: !!map
				})

				if (!BMap || !map) {
					console.error('百度地图API加载失败')
					return
				}

				// 验证BMap对象
				console.log('BMap对象:', typeof BMap, BMap)
				console.log('地图实例:', typeof map, map)

				this.BMap = BMap
				this.mapInstance = map
				this.getCurrentLocation()
			},

			mapClick(e) {
				this.center = e.point
				this.reverseGeocode(e.point)
			},
			infoWindowOpen() {
				this.showInfoWindow = true
			},
			infoWindowClose() {
				this.showInfoWindow = false
			},
			locationSuccess(point) {
				this.center = point.point
				this.reverseGeocode(point.point)
			},
			getCurrentLocation() {
				const geolocation = new this.BMap.Geolocation()
				geolocation.getCurrentPosition(r => {
					if (geolocation.getStatus() === window.BMAP_STATUS_SUCCESS) {
						this.center = r.point
						this.reverseGeocode(r.point)
					}
				})
			},
			reverseGeocode(point) {
				const geoc = new this.BMap.Geocoder()
				geoc.getLocation(point, rs => {
					this.addressInfo = rs.address
				})
			},
			handleSearch() {
				const local = new this.BMap.LocalSearch(this.mapInstance, {
					onSearchComplete: results => {
						if (local.getResults().getNumPois() > 0) {
							const firstResult = local.getResults().getPoi(0)
							this.center = firstResult.point
							this.addressInfo = firstResult.title + firstResult.address
						}
					}
				})
				local.search(this.searchText)
			},
			// 修改搜索方法
			searchInCircleArea() {
				try {
					this.clearPreviousResults()
					this.searchPerformed = true
					this.searchCompletedCount = 0
					this.drawSearchAreaCircle()

					this.searchKeywords.forEach(keyword => {
						try {
							const local = new this.BMap.LocalSearch(this.mapInstance, {
								renderOptions: {
									map: this.mapInstance,
									panel: null
								},
								onSearchComplete: results => {
									console.log(results)
									try {
										this.processSearchResults(results, keyword)
										this.searchCompletedCount++

										if (this.searchCompletedCount === this.searchKeywords.length) {
											console.log('所有搜索完成')
										}
									} catch (e) {
										console.error('搜索完成回调错误:', e)
									}
								}
							})

							const center = new this.BMap.Point(this.center.lng, this.center.lat)
							local.searchNearby(keyword, center, this.searchRadius)
						} catch (e) {
							console.error('创建LocalSearch实例失败:', e)
						}
					})
				} catch (e) {
					console.error('搜索过程中发生错误:', e)
				}
			},


			// 修改处理搜索结果方法
			processSearchResults(results, keyword) {

				try {
					const pois = []
					if (results && results.getNumPois() > 0) {
						for (let i = 0; i < Math.min(results.getNumPois(), this.maxResults); i++) {
							const poi = results.getPoi(i)
							if (poi && poi.point && poi.title) {
								pois.push({
									...poi,
									type: keyword,
									distance: this.calculateDistance(poi.point)
								})
							}
						}
					}

					this.searchResults = [...this.searchResults, ...pois]
					if (pois.length > 0) {
						this.displayMarkers(pois)
					}
				} catch (error) {
					console.error('处理搜索结果时出错:', error)
				}
			},

			// 修改清除方法
			clearPreviousResults() {
				this.searchResults = []
				this.resultMarkers.forEach(marker => {
					if (this.mapInstance) {
						this.mapInstance.removeOverlay(marker)
					}
				})
				this.resultMarkers = []
			},

			// 绘制搜索范围圆形
			drawSearchAreaCircle() {
				if (this.circleOverlay) {
					this.mapInstance.removeOverlay(this.circleOverlay)
				}

				const center = new this.BMap.Point(this.center.lng, this.center.lat)
				this.circleOverlay = new this.BMap.Circle(center, this.searchRadius, {
					strokeColor: "blue",
					strokeWeight: 2,
					strokeOpacity: 0.5,
					fillColor: "#BDE8FF",
					fillOpacity: 0.3
				})
				this.mapInstance.addOverlay(this.circleOverlay)
			},
			// 计算距离
			calculateDistance(point) {
				const center = new this.BMap.Point(this.center.lng, this.center.lat)
				return Math.round(this.mapInstance.getDistance(center, point))
			},

			// 显示标记点
			// 修改 displayMarkers 方法
			displayMarkers(pois) {
				console.log('开始显示标记点，POIs数量:', pois.length)

				if (!pois || pois.length === 0) {
					console.log('没有POI需要显示')
					return
				}

				pois.forEach((poi, index) => {
					console.log(`处理第${index}个POI:`, poi)

					// 验证必要数据
					if (!poi.point || !poi.title) {
						console.warn('标记点数据不完整:', poi)
						return
					}

					try {
						// 验证地图实例
						if (!this.mapInstance) {
							console.error('地图实例不存在')
							return
						}

						console.log('创建标记点...')
						const marker = new this.BMap.Marker(poi.point)
						console.log('标记点创建成功:', marker)

						const infoWindow = new this.BMap.InfoWindow(`
			        <div style="margin:0;line-height:1.5;font-size:13px;">
			          <h4>${poi.title}</h4>
			          <p>类型: ${poi.type || '未知'}</p>
			          <p>地址: ${poi.address || '无地址信息'}</p>
			          <p>距离: ${poi.distance || 0}米</p>
			        </div>
			      `)

						marker.addEventListener('click', () => {
							console.log('点击标记点:', poi)
							if (this.mapInstance) {
								this.mapInstance.openInfoWindow(infoWindow, poi.point)
							} else {
								console.error('地图实例不存在，无法打开信息窗口')
							}
						})

						console.log('添加标记点到地图...')
						this.mapInstance.addOverlay(marker)
						this.resultMarkers.push(marker)
						console.log('标记点添加完成')

					} catch (error) {
						console.error('创建标记点失败:', error, poi)
					}
				})

				console.log('所有标记点处理完成，总数:', this.resultMarkers.length)
			},


			// 新增方法：定位到指定点
			centerMap(point) {
				this.center = point
				this.zoom = 18
			}

		}
	}
</script>
<style scoped>
	.map-container {
		position: relative;
		width: 100%;
		height: 800px;
		/* 使用视口高度确保有高度 */
	}

	.bm-view {
		width: 100%;
		height: 100%;
		/* 确保地图视图占满容器 */
	}

	.search-controls {
		position: absolute;
		top: 20px;
		left: 20px;
		z-index: 1000;
		background: rgba(255, 255, 255, 0.95);
		padding: 15px;
		border-radius: 8px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
		min-width: 300px;
		max-height: 80vh;
		overflow-y: auto;
	}

	/* 其他样式保持不变 */
	.result-panel {
		margin-top: 15px;
		border-top: 1px solid #eee;
		padding-top: 10px;
	}

	.result-count {
		font-size: 14px;
		color: #666;
		margin-bottom: 10px;
	}

	.result-list {
		max-height: 300px;
		overflow-y: auto;
	}



	.result-item {
		padding: 10px;
		border-bottom: 1px solid #f0f0f0;
		cursor: pointer;
		transition: background-color 0.2s;
	}

	.result-item:hover {
		background-color: #f5f5f5;
	}

	.result-item:last-child {
		border-bottom: none;
	}

	.item-header {
		display: flex;
		align-items: center;
		margin-bottom: 5px;
	}

	.item-type {
		font-size: 12px;
		padding: 2px 6px;
		border-radius: 3px;
		margin-right: 8px;
	}

	.item-type.theater {
		background-color: #e3f2fd;
		color: #1976d2;
	}

	.item-type.stadium {
		background-color: #e8f5e9;
		color: #388e3c;
	}

	.item-title {
		font-weight: 500;
		font-size: 14px;
		flex: 1;
	}

	.item-details {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.item-distance {
		font-size: 12px;
		color: #888;
	}

	.no-results {
		margin-top: 15px;
		padding: 10px;
		text-align: center;
		color: #999;
		font-size: 14px;
	}
</style>